
package com.scalar.chiptrack.operations.process.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.operations.process.ProcessStep;
import com.scalar.chiptrack.operations.process.VendorLocation;
import com.scalar.chiptrack.operations.process.dao.ClassStoreDAO;
import com.scalar.chiptrack.operations.process.dao.ProductDao;
import com.scalar.chiptrack.operations.process.dao.VendorLocationDAO;
import com.scalar.chiptrack.operations.process.dao.ProcessTrackDAO;
import com.scalar.chiptrack.operations.process.forms.ClassStoreForm;
import com.scalar.chiptrack.operations.vendor.dao.VendorDAO;
import com.scalar.chiptrack.users.User;

public class ClassStoreAction extends ChipTrackAction {
       
    public ClassStoreAction() {
    }
    
    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response) 
                                  throws Exception {
        
                                      
        String STEP_TYPE = "Class Store";
        String action = request.getParameter("action");
		HttpSession session = request.getSession (false);
		
		User user = (User)session.getAttribute (SessionKeys.USER_KEY);
		if (user == null)
		{
			return (mapping.findForward ("login"));
		}
        if ((action != null) && (action.equalsIgnoreCase("save"))) {
            
            DBTransaction dbTransaction = null;
            boolean success = false;

            ClassStoreForm csForm = (ClassStoreForm) form;
            
            HashMap errors = validateForm (csForm);
            if ((errors != null) && (errors.isEmpty() == false)) 
            {
                request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
            }
            else 
            {
            	int processStepId = -1;
				processStepId = csForm.getProcessStepId();

				// added by ravikanth on 18 Aug 2003 to check for duplicate part numbers in Product Map Table
				String[] partNumbers = new String[csForm.getDupProductName().length+1];
				partNumbers[0] = csForm.getProductName();
				for(int i=0; i < csForm.getDupProductName().length ; i++)
				{
					partNumbers[i+1] = csForm.getDupProductName()[i];
				}
				// added by ravikanth on 16 Sep 2003 
				// check for duplicates in Product_Map_Table
				String dupNames = ProductDao.checkDupInProductMapTable(partNumbers,processStepId,STEP_TYPE);
				if( dupNames.length() > 0 )
				{
					ArrayList vendorLocations = null;
					errors.put ("Part Numbers Already exists ", dupNames );
                    // changed by hareesh on 27th September 2003
                    // -- START --
                    vendorLocations = getAllVendorLocations(request);
                    if(vendorLocations == null){
					    if(processStepId!=-1)
					    {
						    vendorLocations = VendorDAO.getClassStoreLocations (processStepId);;
					    }
					    else
					    {
						    vendorLocations = VendorDAO.getClassStoreLocations ();
					    }
                    }
                    // -- ENd --

					request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);
					request.setAttribute( "classStoreForm" , csForm );
					request.setAttribute( "vendorLocations" , vendorLocations );
					return ( mapping.findForward("failure") );
				}
				// upto here

				ArrayList locations = getVendorLocations(request);

                try {
                    // start transaction 
                    dbTransaction = DBTransaction.getInstance();
                    dbTransaction.begin();

					if(processStepId==-1)
					{
						// Step 1
						// insert a record into Process_Step table and get the process step id
						processStepId = ProcessStep.getProcessStepID (dbTransaction, STEP_TYPE, STEP_TYPE, csForm.getComments());

						// Step 2
						// Store Product Table information
						ProductDao.saveProcessStepProduct (dbTransaction, 
												   processStepId, 
												   csForm.getProductName(), 
												   csForm.getBaseProductId());

						// Step 3
						// insert a row in Inventory_Step table
						ClassStoreDAO.storeClassStoreData (dbTransaction, processStepId, csForm);

						// Step 4
						// Update nextStepID in the previousStepID row
						ProductDao.updateNextProcessStepId (dbTransaction, csForm.getPreviousStepId(), processStepId);

						// Step 5
						// Save vendor locations
					   
						if ((locations != null) && (locations.size() > 0)) {
							VendorLocationDAO.saveVendorLocations (dbTransaction, processStepId, locations.iterator());
						}
						
						//Added by ravikanth on 18 Sep 2003 
						// Step 6		
						// Save Duplicate names into Product_Map_Table
						if( csForm.getDupProductName() != null && csForm.getDupProductName().length > 0)
						{
							ProductDao.saveProductMap( dbTransaction , processStepId , csForm.getDupProductName() , locations );
						}

                        // Added by hareesh on 7 October 2003
                        // Step 7
                        // Change Status from Incomplete -> InProcess
                        ProcessTrackDAO.updateTestTrack( dbTransaction, processStepId , csForm.getTrackId() , csForm.getStepName(), "Inprocess" );

					}
					else
					{
						// Step 1
						// update Process_Step table
						ProcessStep.updateProcessStepID(dbTransaction,csForm.getStepName(),STEP_TYPE,csForm.getComments(),processStepId);

						//Step 2
						//Update Product table
						ProductDao.updateProcessStepProduct(dbTransaction,processStepId,csForm.getProductName(),
												   csForm.getBaseProductId());

						// Step 3
						// Update Inventory_Step table
						ClassStoreDAO.updateClassStoreData (dbTransaction, processStepId, csForm);

						// Step 4
						// Save vendor locations
					    VendorLocationDAO.deleteVendorLocations(dbTransaction,processStepId);
						if ((locations != null) && (locations.size() > 0)) 
						{
							VendorLocationDAO.saveVendorLocations (dbTransaction, processStepId, locations.iterator());
						}
						
						//Added by ravikanth on 18 Sep 2003 
						// Step 5	
						// Save Duplicate names into Product_Map_Table
						if( csForm.getDupProductName() != null && csForm.getDupProductName().length > 0)
						{
							ProductDao.saveProductMap( dbTransaction , processStepId , csForm.getDupProductName() , locations );
						}	
					}
                    
                   // End transaction
                    success = true;
                }
                catch (ScalarException se) {
                    // exception while storing Die Bank information into databse
                    // log it
                    se.getRootCause().printStackTrace();
                }
                finally {
                    // Rollback or Commit the Transaction

                    if (success == true) {
                        dbTransaction.commit();
                    }
                    else {
                        dbTransaction.rollback();
                    }
                }
    
                request.setAttribute ("processStepId", processStepId+"");                   // 
                request.setAttribute ("previousStepId", csForm.getPreviousStepId()+"");  // to be used in transport_locations page
                request.setAttribute ("trackId", csForm.getTrackId()+"");                  //
                request.setAttribute ("productName", csForm.getProductName());            // 
                request.setAttribute ("stepName", csForm.getStepName());                   //
                request.setAttribute ("baseProductId", csForm.getBaseProductId()+"");      //
                request.setAttribute ("comingFrom", "CLASS_STORE");                        // 
            }
            if (success == true) {
                return (mapping.findForward ("success"));
            }
            // changed by hareesh on 27th Septemeber 2003
            // -- START --
            ArrayList vendorLocations = getAllVendorLocations(request);
            if(vendorLocations == null){
                int processStepId = -1;
                processStepId = csForm.getProcessStepId();
               if(processStepId != -1)
                {
                    vendorLocations = VendorDAO.getClassStoreLocations (processStepId);;
                }
                else
                {
                    vendorLocations = VendorDAO.getClassStoreLocations ();
                }
            }
            // -- END --
            request.setAttribute ("vendorLocations", vendorLocations);
            return (mapping.findForward ("failure"));
        }
        
        int processStepId = Integer.parseInt (request.getParameter ("processStepID"));
        int trackId = -1;
        String trackIdStr = request.getParameter ("trackID");
        if ((trackIdStr != null) && (trackIdStr.trim().length() != 0)) {
            trackId = Integer.parseInt (trackIdStr);
        }
        
        ClassStoreForm csForm = null;
        ArrayList vendorLocations = null;
        
        if (processStepId == -1) {  // New 

            String stepName = request.getParameter ("stepName");
            String productName = request.getParameter ("productName");
            int baseProductId = Integer.parseInt (request.getParameter ("baseProductID"));
            int previousStepId = Integer.parseInt (request.getParameter ("previousStepID"));
            
            csForm = new ClassStoreForm();
            csForm.setProductName (productName);
            csForm.setBaseProductId (baseProductId);
            csForm.setPreviousStepId (previousStepId);
            csForm.setStepName (stepName);
            csForm.setTrackId (trackId);    
            
            vendorLocations = VendorDAO.getClassStoreLocations();
        }
        else		// Existing 
        {  
            csForm = ClassStoreDAO.loadClassStoreData (processStepId);
            csForm.setTrackId (trackId);
            csForm.setProcessStepId (processStepId);
			   
            vendorLocations = VendorDAO.getClassStoreLocations (processStepId);
        }
 
        request.setAttribute ("vendorLocations", vendorLocations);
        request.setAttribute ("classStoreForm", csForm);
        
        return (mapping.findForward("show"));
    }

    
    private HashMap validateForm (ClassStoreForm csForm) {
        
        HashMap errors = new HashMap();
        
        try {
            Integer.parseInt (csForm.getMaxLevel());
        }
        catch (NumberFormatException nfe) {
            errors.put ("Max Level", "Invalid number entered for Max Level");
        }
        
        try {
            Integer.parseInt (csForm.getMinLevel());
        }
        catch (NumberFormatException nfe) {
            errors.put ("Min Level", "Invalid number entered for Min Level");
        }
        
        try {
            Integer.parseInt (csForm.getMaxTime());
        }
        catch (NumberFormatException nfe) {
            errors.put ("Max Time", "Invalid number entered for Max Time");
        }
        
        return errors;
    }
    
    private ArrayList getVendorLocations (HttpServletRequest request) {
        
        ArrayList vendorLocations = new ArrayList();
        
        String[] locationName = request.getParameterValues("locationName");
        if (locationName == null) {
            return null;
        }
        
	    String[] priority = request.getParameterValues("priority");
	    String[] locationID = request.getParameterValues("locationID");;

        VendorLocation location = null;
        String select = null;
        
        for (int i=0; i<locationName.length; i++) {

            select = request.getParameter("select_"+i);
            if (select != null) {    // check if this row was enabled by the user or not
                                     // save only if its enabled
                               
                location = new VendorLocation (select,
                                                 // priority[i],
                                                // changed by hareesh on 25th August 2003 // not get -1's if value not entered
                                                ( priority[i] !=null && priority[i].trim().length() != 0 ? priority[i] : "0" ),
                                                 locationName[i],
                                                 locationID[i]);
                vendorLocations.add (location);
            }
        }
        
        return vendorLocations;
    }

    private ArrayList getAllVendorLocations (HttpServletRequest request) {

        ArrayList vendorLocations = new ArrayList();
        String[] locationName = request.getParameterValues("locationName");
        if (locationName == null) {
            return null;
        }
	    String[] priority = request.getParameterValues("priority");
	    String[] locationID = request.getParameterValues("locationID");;

        VendorLocation location = null;
        String select = null;

        for (int i=0; i<locationName.length; i++) {
           select = request.getParameter("select_"+i);
           if (select != null) {
               select = "on";
           }else{
               select = "";
           }

            location = new VendorLocation (select,
                                            ( priority[i] !=null && priority[i].trim().length() != 0 ? priority[i] : "0" ),
                                             locationName[i],
                                             locationID[i]);
            vendorLocations.add (location);
            }
        return vendorLocations;
    }

}